/**
 * Filename: MemberActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 14:45
 */
package com.github.postsanf.yinian.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.TransactionsAdapter;
import com.github.postsanf.yinian.bean.YNTransAction;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNTransactionResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class TransactionDetailsActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshlayout;
    private TransactionsAdapter mAdapter;
    private List<YNTransAction> ynTransActionList = new ArrayList<>();
    private boolean isBottom = false;
    private boolean refresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_transactiondetails);
        initView();
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_fanhui).setOnClickListener(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_transactions);
        mRefreshlayout = (SwipeRefreshLayout) this.findViewById(R.id.rv_transactions_swipe_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setOnRefreshListener(TransactionDetailsActivity.this);
        mRefreshlayout.post(new Runnable() {
            @Override
            public void run() {
                mRefreshlayout.setRefreshing(true);
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && (((LinearLayoutManager) layoutManager).findLastVisibleItemPosition()) >= totalItemCount - 1)) {
                    if (isBottom) {
                        return;
                    }
                    LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                    if (state == LoadingFooter.State.Loading) {
                        return;
                    }
                    RecyclerViewStateUtils.setFooterViewState(TransactionDetailsActivity.this, mRecyclerView, 10, LoadingFooter.State.Loading, null);
                    mRecyclerView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadStatus(false);
                        }
                    }, 500);
                }
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(TransactionDetailsActivity.this));
        mAdapter = new TransactionsAdapter(TransactionDetailsActivity.this, ynTransActionList);
        mRecyclerView.setAdapter(mAdapter);
        noticeServiceInit();
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit();
            }
        }, 500);
    }

    // 更新成员数据
    private void updateView(boolean isTop, List<YNTransAction> StatusList) {
        mRefreshlayout.setRefreshing(false);
        if (isTop) {
            if (StatusList.size() > 0) {
                mAdapter.addItemsFromTop(null);
                mAdapter.addItemsFromTop(StatusList);
                mRecyclerView.scrollToPosition(0);
            }
        } else {
            mAdapter.addItemsFromBottom(StatusList);
            if (StatusList.size() == 0) {
                isBottom = true;
                RecyclerViewStateUtils.setFooterViewState(this, mRecyclerView, 10, LoadingFooter.State.TheEnd, null);
            } else {
                RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
            }
        }
        if (refresh) {
            mAdapter.notifyDataSetChanged();
            refresh = false;
        }
    }

    private void loadStatus(boolean isTop) {
        isBottom = false;
        int loadId = mAdapter.getIdByDirection(isTop);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_TRANSACTIONID, String.valueOf(loadId));
        if (loadId != 0) {
            mParam.put(CommonConstants.YNS_TYPE, "loading");
        } else {
            mParam.put(CommonConstants.YNS_TYPE, "initialize");
        }
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/ShowTransactionRecord")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "zzzzzzzz===sss===>" + s);
                        YNTransactionResponse resAlbumStatus = gson.fromJson(s, YNTransactionResponse.class);
                        if (resAlbumStatus != null && ReqUtils.isSuccess(resAlbumStatus.getCode())) {
                            updateView(false, resAlbumStatus.getData());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void noticeServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_TRANSACTIONID, String.valueOf(0));
        mParam.put(CommonConstants.YNS_TYPE, "initialize");
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/ShowTransactionRecord")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "prrrrrr===sss===>" + s);
                        YNTransactionResponse resAlbumMember = gson.fromJson(s, YNTransactionResponse.class);
                        if (resAlbumMember != null && ReqUtils.isSuccess(resAlbumMember.getCode())) {
                            updateView(true, resAlbumMember.getData());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
            case R.id.iv_fanhui:
                finish();
                break;
        }
    }
}